﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTreeList.Columns;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.数据维护
{
    public partial class Form_DepJobNew : DevExpress.XtraEditors.XtraForm
    {
        public Form_DepJobNew()
        {
            InitializeComponent();
            InitializeTreeList();
            InitializeGridView();

            // 添加TreeList的节点点击事件
            treeList1.FocusedNodeChanged += TreeList1_FocusedNodeChanged;
        }
        private string QJdepName = string.Empty;
        private void TreeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            try
            {
                if (e.Node != null)
                {
                    // 获取选中节点的部门ID
                    string depId = e.Node.GetValue("DepId")?.ToString();
                    if (!string.IsNullOrEmpty(depId))
                    {
                        // 更新窗体标题，显示当前选中的部门名称
                        QJdepName = e.Node.GetValue("DepName")?.ToString() ?? "未知部门";
                        this.Text = $"部门职位维护 - {QJdepName}";

                        // 加载该部门的职位信息
                        LoadJob(depId);
                    }
                    else
                    {
                        // 如果没有获取到部门ID，清空职位列表
                        treeList2.DataSource = null;
                        treeList2.RefreshDataSource();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门职位时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form_DepJobNew_Load(object sender, EventArgs e)
        {
            // 加载部门数据
            LoadDepartmentData();
        }

        private void BtnAddDep_Click(object sender, EventArgs e)
        {
            try
            {
                Form_AddDep from = new Form_AddDep();
                from.UpdateType = true;
                DEPModel model = new DEPModel();

                // 获取TreeList当前选中的节点
                var focusedNode = treeList1.FocusedNode;

                if (focusedNode != null)
                {
                    // 如果有选中节点，获取该节点的DepId值作为上级部门ID
                    string selectedDepId = focusedNode.GetValue("DepId")?.ToString();
                    if (!string.IsNullOrEmpty(selectedDepId))
                    {
                        // 设置父部门ID - 这是关键，确保新部门是选中部门的子部门
                        model.SuperiorDepID = selectedDepId;

                        // 可以同时获取选中部门的名称，用于显示
                        string selectedDepName = focusedNode.GetValue("DepName")?.ToString();
                        model.SupplierName = selectedDepName;
                        DialogResult result = MessageBox.Show($"将添加为部门[{selectedDepName}]的子部门\n (是为添加该部门的子部门，否为添加根节点部门，取消为不添加)",
                                  "确认",
                                  MessageBoxButtons.YesNoCancel,
                                  MessageBoxIcon.Information,
                                  MessageBoxDefaultButton.Button2);

                        // 用户确认
                        if (result == DialogResult.Cancel)
                        {
                            return;
                        }
                        if (result == DialogResult.No)
                        {
                            model = new DEPModel();
                        }

                    }
                }
                else
                {
                    // 如果没有选中节点，则添加为根节点
                    model.SuperiorDepID = null;
                    MessageBox.Show("将添加为顶级部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // 将准备好的model传递给表单
                from.Current = model;

                // 显示表单并处理结果
                if (from.ShowDialog() == DialogResult.OK)
                {
                    // 刷新数据
                    LoadDepartmentData();

                    // 尝试找到并选中新添加的节点
                    if (from.Current != null && !string.IsNullOrEmpty(from.Current.DepId))
                    {
                        SelectNodeById(from.Current.DepId);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加部门时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void BtnDelDep_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取TreeList当前选中的节点
                var focusedNode = treeList1.FocusedNode;

                if (focusedNode != null)
                {
                    // 获取部门ID和名称
                    string depId = focusedNode.GetValue("DepId")?.ToString();
                    string depName = focusedNode.GetValue("DepName")?.ToString();

                    if (string.IsNullOrEmpty(depId))
                    {
                        MessageBox.Show("无法获取部门ID，请重新选择", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 检查是否有子节点
                    if (focusedNode.Nodes.Count > 0)
                    {
                        MessageBox.Show("该部门下有子部门，请先删除子部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 显示确认对话框
                    DialogResult result = MessageBox.Show($"确定要删除部门\"{depName}\" 吗？\n删除后将无法恢复！",
                                                          "删除确认",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Warning,
                                                          MessageBoxDefaultButton.Button2);

                    // 用户确认删除
                    if (result == DialogResult.Yes)
                    {
                        // 显示正在处理的提示
                        Cursor = Cursors.WaitCursor;

                        try
                        {
                            HttpClientHelper helper = new HttpClientHelper();
                            // 调用删除API
                            string action = $"WareHouse/DEP/UpdateDelete?Id={depId}";
                            string response = helper.RequestUrlNew(RequestType.Delete, action, string.Empty);

                            if (!string.IsNullOrEmpty(response))
                            {
                                // 解析API响应
                                var apiResult = JsonConvert.DeserializeObject<ApiResult<string>>(response);

                                if (apiResult.Code == ApiEnums.Success)
                                {
                                    MessageBox.Show("部门删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    // 刷新数据
                                    LoadDepartmentData();
                                }
                                else
                                {
                                    MessageBox.Show($"删除部门失败：{apiResult.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            else
                            {
                                MessageBox.Show("删除请求发送失败，请检查网络连接", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"删除操作异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            // 恢复光标
                            Cursor = Cursors.Default;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要删除的部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("删除操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnUptDep_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取TreeList当前选中的节点
                var focusedNode = treeList1.FocusedNode;

                if (focusedNode != null)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    Form_AddDep from = new Form_AddDep();
                    from.UpdateType = false;

                    try
                    {
                        // 创建DEPModel对象并填充数据
                        DEPModel model = new DEPModel();

                        // 从TreeList节点获取数据
                        model.DepId = focusedNode.GetValue("DepId")?.ToString();
                        model.DepName = focusedNode.GetValue("DepName")?.ToString();
                        model.SuperiorDepID = focusedNode.GetValue("SuperiorDepID")?.ToString();

                        // 如果有其他字段，也从节点中获取
                        if (focusedNode.GetValue("IsEnable") != null)
                        {
                            model.IsEnable = Convert.ToBoolean(focusedNode.GetValue("IsEnable"));
                        }

                        if (focusedNode.GetValue("CreatedBy") != null)
                        {
                            model.CreatedBy = focusedNode.GetValue("CreatedBy")?.ToString();
                        }

                        // 安全地转换日期时间
                        if (focusedNode.GetValue("CreatedTime") != null && focusedNode.GetValue("CreatedTime") != DBNull.Value)
                        {
                            model.CreatedTime = Convert.ToDateTime(focusedNode.GetValue("CreatedTime"));
                        }

                        if (focusedNode.GetValue("UpdatedTime") != null && focusedNode.GetValue("UpdatedTime") != DBNull.Value)
                        {
                            model.UpdatedTime = Convert.ToDateTime(focusedNode.GetValue("UpdatedTime"));
                        }

                        // 传递DEPModel对象到编辑窗体
                        from.Current = model;

                        // 恢复光标
                        Cursor = Cursors.Default;

                        // 显示编辑窗体
                        if (from.ShowDialog() == DialogResult.OK)
                        {
                            // 编辑成功后刷新数据
                            LoadDepartmentData();
                        }
                    }
                    catch (FormatException fex)
                    {
                        MessageBox.Show("数据格式错误：" + fex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要修改的部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("修改操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保光标恢复正常
                Cursor = Cursors.Default;
            }
        }

        private void BtnDepClear_Click(object sender, EventArgs e)
        {
            LoadDepartmentData();
        }

        #region 自定义方法
        /// <summary>
        /// 根据ID查找并选中节点
        /// </summary>
        /// <param name="depId">要选中的部门ID</param>
        private void SelectNodeById(string depId)
        {
            try
            {
                // 查找指定ID的节点
                var nodeToSelect = treeList1.FindNodeByFieldValue("DepId", depId);
                if (nodeToSelect != null)
                {
                    // 选中节点
                    treeList1.FocusedNode = nodeToSelect;
                    treeList1.Selection.Clear();
                    treeList1.Selection.Add(nodeToSelect);

                    // 确保节点可见（如果在折叠的节点下，展开父节点）
                    nodeToSelect.Expand(); // 使用正确的Expand方法

                    // 如果有父节点，确保所有父节点都展开
                    var parentNode = nodeToSelect.ParentNode;
                    while (parentNode != null)
                    {
                        parentNode.Expand();
                        parentNode = parentNode.ParentNode;
                    }

                    // 滚动到节点位置
                    treeList1.MakeNodeVisible(nodeToSelect);
                }
            }
            catch (Exception ex)
            {
                // 记录错误但不显示给用户
                Console.WriteLine($"选中节点时出错: {ex.Message}");
            }
        }

        private async void LoadDepartmentData()
        {
            try
            {
                // 构造API请求URL
                string action = $"WareHouse/Dep/GetDep";
                HttpClientHelper helper = new HttpClientHelper();
                // 发送GET请求获取数据
                string result = helper.RequestUrlNew(RequestType.Get, action, string.Empty);

                // 检查结果是否为空
                if (string.IsNullOrEmpty(result))
                {
                    MessageBox.Show("获取部门数据失败，请检查网络连接！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 反序列化结果
                var apiResult = JsonConvert.DeserializeObject<ApiResult<List<DEPModel>>>(result);

                // 检查API返回状态
                if (apiResult.Code == ApiEnums.Success && apiResult.Data != null)
                {
                    // 确保TreeList正确设置
                    treeList1.KeyFieldName = "DepId"; // 设置主键字段
                    treeList1.ParentFieldName = "SuperiorDepID"; // 设置父级字段

                    // 处理返回的数据，构建部门层级关系
                    List<DEPModel> departments = apiResult.Data;

                    // 创建一个DataTable并添加必要的列
                    DataTable dt = new DataTable();
                    dt.Columns.Add("DepId", typeof(string));
                    dt.Columns.Add("DepName", typeof(string));
                    dt.Columns.Add("SuperiorDepID", typeof(string));
                    dt.Columns.Add("IsEnable", typeof(bool));
                    dt.Columns.Add("CreatedTime", typeof(DateTime));

                    // 将所有部门添加到DataTable中
                    foreach (var dep in departments)
                    {
                        object superiorDepId = string.IsNullOrEmpty(dep.SuperiorDepID) ? DBNull.Value : (object)dep.SuperiorDepID;
                        dt.Rows.Add(
                            dep.DepId,
                            dep.DepName,
                            superiorDepId,
                            dep.IsEnable,
                            dep.CreatedTime
                        );
                    }

                    // 绑定数据到TreeList
                    treeList1.DataSource = dt;

                    // 展开所有节点
                    treeList1.ExpandAll();

                    // 如果需要，可以在这里添加其他处理，比如选中第一个节点等
                    if (treeList1.Nodes.Count > 0)
                    {
                        treeList1.FocusedNode = treeList1.Nodes[0];
                    }
                }
                else
                {
                    MessageBox.Show($"获取部门数据失败：{apiResult.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门数据时发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeTreeList()
        {
            // 清除所有列
            treeList1.Columns.Clear();

            // 添加列
            TreeListColumn depIdColumn = treeList1.Columns.Add();
            depIdColumn.Caption = "部门编码";
            depIdColumn.FieldName = "DepId";
            depIdColumn.Visible = false; // 隐藏部门编码列
            depIdColumn.Width = 100;

            TreeListColumn depNameColumn = treeList1.Columns.Add();
            depNameColumn.Caption = "部门名称";
            depNameColumn.FieldName = "DepName";
            depNameColumn.Visible = true; // 只显示部门名称列
            depNameColumn.Width = 200; // 增加宽度以便更好地显示部门名称

            TreeListColumn superiorDepIdColumn = treeList1.Columns.Add();
            superiorDepIdColumn.Caption = "上级部门";
            superiorDepIdColumn.FieldName = "SuperiorDepID";
            superiorDepIdColumn.Visible = false; // 隐藏上级部门列
            superiorDepIdColumn.Width = 100;

            // 设置TreeList属性
            treeList1.KeyFieldName = "DepId"; // 主键字段
            treeList1.ParentFieldName = "SuperiorDepID"; // 父级字段
            treeList1.OptionsView.ShowIndicator = false;
            treeList1.OptionsView.ShowHorzLines = false; // 隐藏水平线，使显示更清爽
            treeList1.OptionsView.ShowVertLines = false; // 隐藏垂直线，使显示更清爽
            treeList1.OptionsView.ShowColumns = false; // 隐藏列头，使显示更简洁
            treeList1.OptionsBehavior.AutoNodeHeight = true; // 自动调整节点高度

            // 启用节点拖拽
            treeList1.AllowDrop = true;
            treeList1.OptionsBehavior.EnableFiltering = true;
            treeList1.OptionsBehavior.Editable = false;
            treeList1.OptionsBehavior.AllowExpandOnDblClick = true;
        }

        private void InitializeGridView()
        {
            // 设置TreeList属性
            treeList2.KeyFieldName = "JobId"; // 主键字段
            treeList2.ParentFieldName = "SuperiorJobID"; // 父级字段 - 使用上级职位ID作为父节点

            // 清除所有列
            treeList2.Columns.Clear();

            // 添加列
            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "JobId",
                Caption = "职位编码",
                Visible = false
            });

            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "JobName",
                Caption = "职位名称",
                Visible = true,
                Width = 200
            });

            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "DepId",
                Caption = "所属部门",
                Visible = false
            });

            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "SuperiorJobID",
                Caption = "上级职位ID",
                Visible = false
            });

            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "SuperiorJobName",
                Caption = "上级职位",
                Visible = true,
                Width = 120
            });

            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "IsEnable",
                Caption = "是否启用",
                Visible = true,
                Width = 80
            });

            treeList2.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn
            {
                FieldName = "CreatedTime",
                Caption = "创建时间",
                Visible = true,
                Width = 150
            });

            // 设置TreeList视图属性
            treeList2.OptionsBehavior.Editable = false;
            treeList2.OptionsView.ShowIndicator = true;
            treeList2.OptionsView.EnableAppearanceEvenRow = true;
            treeList2.OptionsView.ShowHorzLines = true;
            treeList2.OptionsView.ShowVertLines = true;
        }

        private async void LoadJob(string depId)
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                // 构造API请求URL
                string action = $"WareHouse/Job/GetJob?DepId={depId}";
                HttpClientHelper helper = new HttpClientHelper();
                // 发送GET请求获取数据
                string result = helper.RequestUrlNew(RequestType.Get, action, string.Empty);

                // 检查结果是否为空
                if (string.IsNullOrEmpty(result))
                {
                    MessageBox.Show("获取职位数据失败，请检查网络连接！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 反序列化结果
                var apiResult = JsonConvert.DeserializeObject<ApiResult<List<JobModel>>>(result);

                // 检查API返回状态
                if (apiResult.Code == ApiEnums.Success && apiResult.Data != null)
                {
                    // 创建DataTable用于TreeList绑定
                    DataTable dt = new DataTable();
                    dt.Columns.Add("JobId", typeof(string));
                    dt.Columns.Add("JobName", typeof(string));
                    dt.Columns.Add("DepId", typeof(string));
                    dt.Columns.Add("SuperiorJobID", typeof(string));
                    dt.Columns.Add("SuperiorJobName", typeof(string));
                    dt.Columns.Add("IsEnable", typeof(bool));
                    dt.Columns.Add("CreatedTime", typeof(DateTime));

                    // 处理职位层级关系
                    List<JobModel> jobsWithHierarchy = BuildJobHierarchy(apiResult.Data);

                    // 将数据填充到DataTable
                    foreach (var job in jobsWithHierarchy)
                    {
                        object superiorJobId = string.IsNullOrEmpty(job.SuperiorJobID) ? DBNull.Value : (object)job.SuperiorJobID;

                        dt.Rows.Add(
                            job.JobId,
                            job.JobName,
                            job.DepId,
                            superiorJobId,
                            job.SuperiorJobName,
                            job.IsEnable,
                            job.CreatedTime
                        );
                    }

                    // 将数据绑定到TreeList
                    treeList2.DataSource = dt;

                    // 刷新TreeList
                    treeList2.RefreshDataSource();

                    // 展开所有节点以显示层级关系
                    treeList2.ExpandAll();
                }
                else
                {
                    // 如果返回失败或没有数据，清空TreeList
                    treeList2.DataSource = null;
                    treeList2.RefreshDataSource();
                    MessageBox.Show($"获取职位数据失败：{apiResult.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载职位数据时发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 为职位数据构建层级关系，确保SuperiorJobName正确设置
        /// </summary>
        private List<JobModel> BuildJobHierarchy(List<JobModel> jobs)
        {
            // 创建职位ID到职位的映射
            Dictionary<string, JobModel> jobMap = jobs.ToDictionary(j => j.JobId);

            // 确保所有职位的SuperiorJobName字段被正确设置
            foreach (var job in jobs)
            {
                if (!string.IsNullOrEmpty(job.SuperiorJobID) && jobMap.ContainsKey(job.SuperiorJobID))
                {
                    // 设置上级职位名称
                    job.SuperiorJobName = jobMap[job.SuperiorJobID].JobName;
                }
                else
                {
                    // 如果没有上级职位，将SuperiorJobName设置为一个特殊值，以便于分组
                    job.SuperiorJobName = "[无上级职位]";
                }
            }

            return jobs;
        }
        #endregion

        /// <summary>
        /// 新增职位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查是否已选择部门
                var focusedNode = treeList1.FocusedNode;
                if (focusedNode == null)
                {
                    MessageBox.Show("请先选择一个部门，然后再添加职位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中的部门ID和名称
                string depId = focusedNode.GetValue("DepId")?.ToString();
                string depName = focusedNode.GetValue("DepName")?.ToString();

                if (string.IsNullOrEmpty(depId))
                {
                    MessageBox.Show("无法获取部门ID，请重新选择部门", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建职位窗体
                Form_AddJob form = new Form_AddJob();
                form.UpdateType = true; // 新增模式

                // 创建职位对象
                JobModel model = new JobModel();
                model.DepId = depId; // 设置所属部门ID

                // 如果TreeList有选中的节点，可以选择是否添加为其子职位
                var focusedJobNode = treeList2.FocusedNode;
                if (focusedJobNode != null)
                {
                    string jobId = focusedJobNode.GetValue("JobId")?.ToString();
                    string jobName = focusedJobNode.GetValue("JobName")?.ToString();

                    if (!string.IsNullOrEmpty(jobId) && !string.IsNullOrEmpty(jobName))
                    {
                        DialogResult result = MessageBox.Show(
                            $"是否添加为职位[{jobName}]的下级职位?\n" +
                            "选择\"是\"添加为该职位的下级，选择\"否\"添加为普通职位",
                            "确认",
                            MessageBoxButtons.YesNoCancel,
                            MessageBoxIcon.Question,
                            MessageBoxDefaultButton.Button2);

                        if (result == DialogResult.Yes)
                        {
                            // 设置上级职位ID
                            model.SuperiorJobID = jobId;
                            model.SuperiorJobName = jobName;
                            model.DepId = depId;
                            model.DepName = depName;
                        }
                        else if (result == DialogResult.No)
                        {
                            model.DepId = depId;
                            model.DepName = depName;
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                else
                {
                    model.DepId = depId;
                            model.DepName = depName;
                }

                // 设置其他信息
                model.IsEnable = true; // 默认启用
                form.Current = model;

                // 显示职位添加窗体
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // 添加成功后刷新职位列表
                    LoadJob(depId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加职位时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 修改职位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpt_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取TreeList选中节点
                var focusedNode = treeList2.FocusedNode;
                if (focusedNode == null)
                {
                    MessageBox.Show("请先选择要修改的职位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建职位对象并从选中节点获取数据
                JobModel model = new JobModel();
                model.JobId = focusedNode.GetValue("JobId")?.ToString();
                model.JobName = focusedNode.GetValue("JobName")?.ToString();
                model.DepId = treeList1.FocusedNode.GetValue("DepId")?.ToString();
                model.DepName = QJdepName;
                model.SuperiorJobID = focusedNode.GetValue("SuperiorJobID")?.ToString();
                model.SuperiorJobName = focusedNode.GetValue("SuperiorJobName")?.ToString();

                // 获取其他属性
                if (focusedNode.GetValue("IsEnable") != null)
                {
                    model.IsEnable = Convert.ToBoolean(focusedNode.GetValue("IsEnable"));
                }

                if (focusedNode.GetValue("CreatedTime") != null && focusedNode.GetValue("CreatedTime") != DBNull.Value)
                {
                    model.CreatedTime = Convert.ToDateTime(focusedNode.GetValue("CreatedTime"));
                }

                if (string.IsNullOrEmpty(model.JobId))
                {
                    MessageBox.Show("无法获取职位ID", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建职位编辑窗体
                Form_AddJob form = new Form_AddJob();
                form.UpdateType = false; // 修改模式
                form.Current = model;

                // 显示职位编辑窗体
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // 编辑成功后刷新职位列表
                    string depId = model.DepId;
                    if (!string.IsNullOrEmpty(depId))
                    {
                        LoadJob(depId);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改职位时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除职位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnDel_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取TreeList选中节点
                var focusedNode = treeList2.FocusedNode;
                if (focusedNode == null)
                {
                    MessageBox.Show("请先选择要删除的职位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取职位ID和名称
                string jobId = focusedNode.GetValue("JobId")?.ToString();
                string jobName = focusedNode.GetValue("JobName")?.ToString();
                string depId = focusedNode.GetValue("DepId")?.ToString();

                if (string.IsNullOrEmpty(jobId))
                {
                    MessageBox.Show("无法获取职位ID", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 检查是否有子节点（下级职位）
                if (focusedNode.Nodes.Count > 0)
                {
                    MessageBox.Show("该职位有下级职位，请先删除下级职位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 显示确认对话框
                DialogResult result = MessageBox.Show(
                    $"确定要删除职位\"{jobName}\"吗？\n删除后将无法恢复！",
                    "删除确认",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2);

                // 用户确认删除
                if (result == DialogResult.Yes)
                {
                    try
                    {
                        // 显示等待光标
                        Cursor = Cursors.WaitCursor;
                        HttpClientHelper helper = new HttpClientHelper();
                        // 调用删除API
                        string action = $"WareHouse/Job/UpdateDelete?Id={jobId}";
                        string response = helper.RequestUrlNew(RequestType.Delete, action, string.Empty);

                        if (!string.IsNullOrEmpty(response))
                        {
                            // 解析API响应
                            var apiResult = JsonConvert.DeserializeObject<ApiResult<string>>(response);

                            if (apiResult.Code == ApiEnums.Success)
                            {
                                MessageBox.Show("职位删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                // 刷新数据
                                if (!string.IsNullOrEmpty(depId))
                                {
                                    LoadJob(depId);
                                }
                            }
                            else
                            {
                                MessageBox.Show($"删除职位失败：{apiResult.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("删除请求发送失败，请检查网络连接", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    finally
                    {
                        // 恢复光标
                        Cursor = Cursors.Default;
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show($"删除职位时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新职位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClear_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前选中的部门节点
                var focusedNode = treeList1.FocusedNode;
                if (focusedNode != null)
                {
                    // 获取部门ID
                    string depId = focusedNode.GetValue("DepId")?.ToString();
                    if (!string.IsNullOrEmpty(depId))
                    {
                        // 重新加载该部门的职位信息
                        LoadJob(depId);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择一个部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新职位信息时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}